import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import Loading from '@/components/Loading';
import HistoryTable from '@/components/withdraw/HistoryTable';
import Stats from '@/components/withdraw/Stats';
import API from '@/http';

function Withdraw() {
  const [isLoading, setIsLoading] = useState(true);
  const [page, setPage] = useState(1);
  const [datas, setDatas] = useState<any[]>([]);
  const [totalPage, setTotalPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const { t, i18n } = useTranslation();
  const [total, setTotal] = useState({
    title: t('totalProfitGain'),
    value: 0,
  });
  const [allow, setAllow] = useState({
    title: t('withdrawableAmount'),
    value: 0,
  });
  const [doing, setDoing] = useState({
    title: t('applicationProgress'),
    value: 0,
  });
  const [finished, setFinished] = useState({
    title: t('amountBilled'),
    value: 0,
  });

  useEffect(() => {
    API.Withdraw.logList({ page, limit })
      .then((data) => {
        setTotal({
          title: t('totalProfitGain'),
          value: data.total_profit,
        });
        setAllow({
          title: t('withdrawableAmount'),
          value: data.allow_profit,
        });
        setDoing({
          title: t('applicationProgress'),
          value: data.doing_profit,
        });
        setFinished({
          title: t('amountBilled'),
          value: data.finished_profit,
        });

        setDatas(data.list);
        setTotalPage(data.total_page);
      })
      .finally(() => setIsLoading(false));
  }, [page, limit, i18n.language]);

  return (
    <div className="flex flex-col items-center space-y-12 md:mx-auto md:pt-12 md:pt-24">
      <h1 className="mx-5 hidden text-center text-16 leading-140 text-ff md:block md:text-20">
        {t('incomeStatement')}
      </h1>
      {isLoading ? (
        <Loading />
      ) : (
        <>
          <div className="flex w-full flex-col px-2 pb-2">
            <Stats {...{ total, allow, doing, finished }} />
            <HistoryTable
              {...{ datas, totalPage, currentPage: page, limit }}
              onPageClick={(page) => setPage(page)}
            />
          </div>
        </>
      )}
    </div>
  );
}

export default Withdraw;
